// Project name:JavaRedis
// Creator:muhong
// Date time:2022/12/27,10:47 上午
// Name:DefaultFutureListeners

package org.gmh.util.concurrent;

import java.util.Arrays;

public class DefaultFutureListeners {

    private GenericFutureListener<? extends Future<?>>[] listeners;
    private int size;
    private int progressiveSize;

    DefaultFutureListeners(GenericFutureListener<? extends Future<?>> first,
                                  GenericFutureListener<? extends Future<?>> second) {
        listeners = new GenericFutureListener[2];
        listeners[0] = first;
        listeners[1] = second;
        size = 2;
        if (first instanceof GenericProgressiveFutureListener) {
            progressiveSize++;
        }
        if (second instanceof GenericProgressiveFutureListener) {
            progressiveSize++;
        }
    }


    public void add(GenericFutureListener<? extends Future<?>> l) {
        GenericFutureListener<? extends Future<?>>[] listeners = this.listeners;
        int size = this.size;
        if (size == listeners.length) {
            this.listeners = listeners = Arrays.copyOf(listeners, size << 1);
        }
        listeners[size] = l;
        this.size = size + 1;
        if (l instanceof GenericProgressiveFutureListener) {
            this.progressiveSize++;
        }
    }

    public void remove(GenericFutureListener<? extends Future<?>> l) {
        GenericFutureListener<? extends Future<?>>[] listeners = this.listeners;
        int size = this.size;
        for (int i = 0; i < size; i++) {
            if (listeners[i] == l) {
                int listenerToMove = size - i - 1;
                if (listenerToMove > 0) {
                    System.arraycopy(listeners, i + 1, listeners, i, listenerToMove);
                }
                listeners[--size] = null;
                this.size = size;
                if (l instanceof GenericProgressiveFutureListener) {
                    this.progressiveSize--;
                }
                return;
            }
        }
    }

    public GenericFutureListener<? extends Future<?>>[] listeners(){
        return this.listeners;
    }

    public int size(){
        return size;
    }

    public int progressiveSize(){
        return this.progressiveSize;
    }
}
